<template>
  <div class="emptyBox">
    <addPlan @add='handleAdd' @batchImportEmpty='batchImportEmpty' ref="addPlan" :seeFlag="see" plan-tag="IE" :term-dis="false"></addPlan>
    <goodTable style="margin-top:20px" ref="goodTable" @edit="edit" :seeFlag="see"></goodTable>
    <div class="btn" v-if="!see">
      <el-button type="primary"
                 @click="add">生成计划</el-button>
    </div>
    <el-dialog title=""
               :visible.sync="dialogVisible"
               width="65%"
               :before-close="handleClose">
      <addGoods ref="addGoods" :seeFlag="see" v-if="dialogVisible"></addGoods>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="save" v-if="!see">保存</el-button>
        <el-button type="primary"
                   @click="dialogVisible = false" v-if="!see">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import addPlan from './module/addPlan.vue'
import goodTable from './module/goodTable.vue'
import addGoods from './module/addGoods.vue'
import * as XLSX from 'xlsx'
import { isStringEmpty } from '@/utils/StringUtil' // 导入工具函数
export default {
  name: 'emptyBox',
  components: { addPlan, goodTable, addGoods,newLeftMenu2 },
  data() {
    return {
      dialogVisible: false,
      see:false,
      oldFormJson:'',
      dataList: {}
    }
  },
//通过路由规则，离开该组件时被调用
beforeRouteLeave (to, from, next) {
      console.log('About--beforeRouteLeave',to,from)
      let nowJsonData = JSON.stringify(this.$refs.addPlan.form)
      let oldFormJson = JSON.stringify(this.$refs.addPlan.oriForm)
      // let nowJsonData1 = JSON.stringify(this.$refs.addPlan.form)
      // let oldFormJson1 = JSON.stringify(this.$refs.addPlan.oriForm)
      // console.log('================================ ',nowJsonData,' 000000000000000000000000 ',oldFormJson) //;
      if(nowJsonData!=oldFormJson && to.query.name != 'boxGoods'){
      // if(nowJsonData!=oldFormJson || nowJsonData1!=oldFormJson1){
      // if(this.tableData!= []){
        this.$nextTick(()=>{
          this.$confirm('存在未提交信息，确认关闭？',{
            closeOnHashChange:false,
            closeOnClickModal:false,
            distinguishCancelAndClose:true,
            closeOnPressEscape:false,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
          })
                .then(_ => {
                  console.log('这边有问题',this.$route.path);
                  // console.log('这边有问题',this.$route.current);
                  this.$store.commit('setActiveMenuPath',next.fullPath)
                  // this.$router.push(to.fullPath)
                  next()
                })
                .catch(_ => {
                  console.log('是取消！！！！！！！！！！！！！！！！！',from.fullPath);
                  this.$store.commit('setActiveMenuPath',from.fullPath)
                  // this.$route.path = from.fullPath
                  // this.$router.push(from.fullPath)
                  // console.log('看看路由',this.$route.path)
                  this.$nextTick(()=>{
                    // this.$refs.newLeftMenu2.refresh = !this.$refs.newLeftMenu2.refresh
                    let path = {
                      index: from.fullPath,
                    }
                    // this.$refs.newLeftMenu2.getActivePath(path) 
                    this.$refs.newLeftMenu2.getPath(from.fullPath)
                    this.$refs.newLeftMenu2.linkTab(from.fullPath)
                  })
                  // this.$refs.newLeftMenu2.linkTab(from.fullPath)
                  // console.log('path: ' + from.fullPath,this.$route.path);
                });
        })
      }else{
        next()
      }
  },
  methods: {
    initDictData() {
          this.dataList = {
              cstCoperMap: {}, //cus 持箱人
              INTERNALFG_MAP: {}, //INTERNALFG_IM 贸易类型
              portsMap: {},
              boxMap: []//boxSize 箱型
          }
          // 持箱人
          this.$api.getCustomerRelations({})
              .then((res) => {
                  this.dataList.cstCoperMap = new Map(res.data.map(obj => [obj.relationTenantName, obj.relationTenantId]))
              }).catch()
          // 贸易类型
          this.$api.refCode({domain: 'INTERNALFG_IM', })
              .then((res) => {
                  this.dataList.INTERNALFG_MAP = new Map(res.data.data.map(obj => [obj.meaning, obj.lowValue]));
              }).catch()
          // 港口
          this.$api.port().then((res) => {
              this.dataList.portsMap = new Map(res.data.data.map(obj => [obj.portlocnnm, obj.portcd]));
          }).catch()
          // 箱型
          this.$api.containerTypeSizeInfo()
              .then((res) => {
                  this.dataList.boxMap = new Map(res.data.data.map(obj => [obj.containerType+obj.containerSize, obj.isoCode]));
              }).catch()
      },
      batchImportEmpty(file) {
          // console.log(this.dataList)
          const isExcel = /\.(xlsx|xls|csv)$/.test(file.name)
          if (!isExcel) {
              this.$message.error('只能上传 .xlsx、.xls、.csv 文件!')
              return false
          }

          // 创建一个文件读取器
          const reader = new FileReader();
          reader.onload = (e) => {
              // 1、拿取到json数组
              const data = new Uint8Array(e.target.result)
              const workbook = XLSX.read(data, { type: 'array' })
              const firstSheetName = workbook.SheetNames[0]
              const worksheet = workbook.Sheets[firstSheetName]
              const jsonArray = XLSX.utils.sheet_to_json(worksheet, { header: 1 })
              if(jsonArray.length < 2){
                  this.$message.error('无数据导入')
                  return false
              }

              // 简单空校验  并合并一箱多货  key为箱号 value 为 货数组
              const jsonMap = new Map();
              for(let i = 1 ; i < jsonArray.length ; i++){
                  let itemBox = jsonArray[i]
                  // 0-10 必填项不允许为空
                  if (isStringEmpty(itemBox[0])
                      || isStringEmpty(itemBox[1]) || isStringEmpty(itemBox[2])
                      || isStringEmpty(itemBox[3]) || isStringEmpty(itemBox[4])
                      || isStringEmpty(itemBox[5]) || isStringEmpty(itemBox[6])
                      || isStringEmpty(itemBox[7]) || isStringEmpty(itemBox[8])) {
                      this.$message.error('A-I列存在必填项为空,请检查')
                      return  false
                  }

                  if(!isStringEmpty(itemBox[1]) && this.dataList.cstCoperMap.get(itemBox[1]) == null){
                      this.$message.error(itemBox[1]+'持箱人不存在!')
                      return  false
                  }

                  if(!isStringEmpty(itemBox[2]) && this.dataList.INTERNALFG_MAP.get(itemBox[2]) == null){
                      this.$message.error('贸易类型填写错误!')
                      return  false
                  }

                  if(!isStringEmpty(itemBox[6]) && this.dataList.boxMap.get(itemBox[6]+itemBox[7]) == null){
                      this.$message.error(itemBox[6]+itemBox[7]+'箱型尺寸填写错误!')
                      return  false
                  }

                  if(!isStringEmpty(itemBox[3]) && this.dataList.portsMap.get(itemBox[3]) == null){
                      this.$message.error(itemBox[3]+'不存在!')
                      return  false
                  }

                  if(!isStringEmpty(itemBox[4]) && this.dataList.portsMap.get(itemBox[4]) == null){
                      this.$message.error(itemBox[4]+'不存在!')
                      return  false
                  }

                  if(!isStringEmpty(itemBox[5]) && this.dataList.portsMap.get(itemBox[5]) == null){
                      this.$message.error(itemBox[5]+'不存在!')
                      return  false
                  }

                  const key = itemBox[0];
                  // 如果key已存在，则使用数组存储所有对应的value 10 - 15 为货
                  let goodsJson =
                      {
                          "planGoods": {
                              "billno": itemBox[10] // 提单号
                          }
                      }
                  if (jsonMap.has(key)) {
                      jsonMap.get(key).push(goodsJson);
                  } else {
                      jsonMap.set(key, [goodsJson]);
                  }
              }

              // 列表清空
              this.$refs.goodTable.tableData = []
              this.$refs.goodTable.myUpdate()

              // 记录箱号遍历标志
              let traversedSet = new Set();
              for(let i = 1 ; i < jsonArray.length ; i++){
                  let itemBox = jsonArray[i]
                  if(traversedSet.has(itemBox[0])){
                      continue;
                  }
                  traversedSet.add(itemBox[0])
                  let boxJson = {
                      "attachOperation": "WG",
                      "attachOperationName": "外港",
                      "containerGoodList": jsonMap.get(itemBox[0]),
                      "data": "",
                      "cntrno": itemBox[0], // 箱号
                      "cstCopercd": this.dataList.cstCoperMap.get(itemBox[1]),
                      "cstCopercdName": itemBox[1], // 持箱人
                      "internalfg": this.dataList.INTERNALFG_MAP.get(itemBox[2]), // 贸易类型
                      "internalfgName": itemBox[2], // 贸易类型
                      "potLdport": this.dataList.portsMap.get(itemBox[3]),  // 装货港
                      "potLdportName": itemBox[3],  // 装货港
                      "potUnldport": this.dataList.portsMap.get(itemBox[4]), // 卸货港
                      "potUnldportName": itemBox[4], // 卸货港
                      "potDstnport": this.dataList.portsMap.get(itemBox[5]), // 目的港
                      "potDstnportName": itemBox[5], // 目的港
                      "typeSize": [
                          itemBox[6], // 箱型
                          itemBox[7] // 箱尺寸
                      ],
                      "ctypecd": itemBox[6], // 箱型
                      "cszCsizecd": itemBox[7], // 箱尺寸
                      "isocd": this.dataList.boxMap.get(itemBox[6]+itemBox[7]),
                      "cweight": itemBox[8], // 箱货总重（吨）
                      "sealno": itemBox[9] // 铅封号
                  }
                  this.$refs.goodTable.tableData.push(boxJson)
              }
              this.$refs.goodTable.myUpdate()
          };
          reader.readAsArrayBuffer(file);
          // 如果需要继续上传文件，返回 true
          return false;
      },
    handleClose(done){
      let nowJsonData = this.$refs.addGoods.getNowData()
      console.log(this.oldFormJson , '--------------------' , nowJsonData);
      if(this.oldFormJson == nowJsonData){
        this.dialogVisible=false
      }else{
        this.$confirm('存在未提交信息，确认关闭？')
            .then(_ => {
              done();
            })
            .catch(_ => {});
      }
    },
    save(){
      this.$refs.addGoods.$refs.form.validate((valid) => {
          if(valid){
            this.save1()
          }else{
            return false
          }
      });
      //return result
    },
    save1(){
      let c=JSON.parse(JSON.stringify(this.$refs.addGoods.form))
      //let c1=JSON.parse(JSON.stringify(this.$refs.addGoods.form1))
      //console.log(c)
     // console.log(c.index)
      if(undefined!==c.index){
        //console.log(99999999)
        this.$set(this.$refs.goodTable.tableData,c.index,c)
        //this.$set(this.$refs.goodTable.tableData1,c.index,c1)
        this.$refs.goodTable.myUpdate()
      }else{
        console.log(666)
        this.$refs.goodTable.tableData.push(c)
        //this.$refs.goodTable.tableData1.push(c1)
      }
      this.$refs.addGoods.form={}
      //this.$refs.addGoods.$refs.form.resetFields()
      //this.$refs.addGoods.form1={}
      this.dialogVisible = false
    },
    edit(e,e1,index){
      this.dialogVisible=true
      this.$nextTick(res=>{
        e.index=index
        this.$refs.addGoods.form= JSON.parse(JSON.stringify(e))
        
        /* 存旧数据 */
        this.oldFormJson = JSON.stringify(e)
        /*  */

        //this.$refs.addGoods.form1=e1
      })
    },
    getInfo(){
      this.$nextTick(()=>{
        if(undefined!==this.$route.query.id){
          if('see'===this.$route.query.state){
            this.see=true
          }else{
            this.see=false
          }
          this.$api.contentSelectAll({
            id:this.$route.query.id
          }).then(res=>{
            let data=res.data.data[0]
            let name=this.$refs.addPlan.form.cstCoperName
            let plan=this.$refs.addPlan.form.planTagName
            this.$refs.addPlan.form=JSON.parse(JSON.stringify(data))
            this.$refs.addPlan.form.cstCoperName=name
            this.$refs.addPlan.form.planTagName=plan
            
            this.$refs.addPlan.$refs.myUpload.file=JSON.parse(JSON.stringify(data.planAttachmentList))
            //console.log(this.$refs.addPlan.form)
            //this.$refs.boxNum.form=JSON.parse(JSON.stringify(data.vanUseRequirements))
            this.$refs.goodTable.tableData=JSON.parse(JSON.stringify(data)).planContainers
            //this.$refs.boxNum.form.termCode=JSON.parse(JSON.stringify(data)).termCode
          }).catch()
        }
      })
    },
    set(val){
      console.log(val)
      this.$refs.addPlan.set(val)
    },
    link(){
      this.$router.push({
        query:{
          name:'boxGoods'
        },
        name:'success'
      })
    },
    checkPlan(){
      let result=false
      this.$refs.addPlan.$refs.form.validate((valid) => {
            result=valid
      });
      return result
    },
    handleAdd(){
      this.dialogVisible=true
      this.$nextTick(()=>{
        /* 存旧数据 */
        this.oldFormJson = this.$refs.addGoods.getNowData()
        /*  */
      })
    },
    add(){
      this.$refs.addPlan.loading=true
      let that=this
      let formPlan = this.checkPlan()
      if(!(formPlan)){
        this.$refs.addPlan.loading=false
        return 
      }
      if(0===this.$refs.goodTable.selection.length){
        this.$refs.addPlan.loading=false
        this.$message.error('请选择箱！')
        return
      }
      let planContainers=this.$refs.goodTable.selection
      let form=this.$refs.addPlan.form
      form.planContainers=planContainers
      let par=''
      if(undefined===form.id||null===form.id){
        par='JK_Add'
      }else{
        par='JK_Edit'
      }
      this.$api.shipE(form,par).then(res=>{
        if(200===res.code){
          this.$message.success({message:undefined!==form.id?'编辑成功!':'新增成功!',onClose(){that.link()}})
        }else{
          this.$refs.addPlan.loading=false
          //this.$message.error(res.message)
        }
      }).catch(res=>{
        this.$refs.addPlan.loading=false
        //this.$message.error(res.message)
      })
    }
  },

  computed: {},

  mounted() {
    this.getInfo()
    this.initDictData()
  },
}
</script>
<style lang='scss' scoped>
:deep .el-input.is-disabled .el-input__inner {
  color: #666

}
:deep .el-textarea.is-disabled .el-textarea__inner {
  color: #666
}
.emptyBox {
  background-color: #fff;
  padding: 15px 30px 40px 30px;
}
:deep.el-dialog__footer {
  text-align: center;
  .el-button {
    color: #fff;
    background: #0f47b8;
    height: 30px;
    width: 100px;
    padding: 5px 10px;
  }
}
:deep.el-dialog__header {
  padding: 0;
}
:deep.el-dialog__body {
  padding: 20px;
}

.btn{
  text-align: center;
  margin-top: 20px;
  .el-button{
    background: #0f47b8;
    height: 30px;
    padding: 5px 10px;
  }
}
</style>